package com.yehuo.app.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yehuo.app.entity.Page;
import com.yehuo.app.entity.Robot;
import com.yehuo.app.entity.User;
import com.yehuo.app.mapper.RobotMapper;
import com.yehuo.app.mapper.UserMapper;
import com.yehuo.app.model.R;
import com.yehuo.app.model.Result;
import com.yehuo.app.util.APiUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 机器人管理
 */
@RestController
@RequestMapping("/robot")
public class RobotController {

    @Resource
    private RobotMapper robotMapper;


    @Resource
    private UserMapper userMapper;

    @RequestMapping("/list")
    public R<Robot> list(Page page) {
        PageHelper.startPage(page.getPage(), page.getLimit());
        List<Robot> list = robotMapper.selectList(null);
        list.forEach(o -> {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("_uid", o.getUid());
            User user = userMapper.selectOne(queryWrapper);
            o.setNickname(user.getNickname());
            o.setName(user.getName());
            o.setAvatar(user.getAvatar());
            o.setCreateTime(user.getCreateTime());
        });
        PageInfo<Robot> pageInfo = new PageInfo<>(list);
        R<Robot> result = new R<Robot>((int) pageInfo.getTotal(), pageInfo.getList());
        return result;
    }

    /**
     * 注册/更新机器人
     *
     * @param
     * @return
     */
    @RequestMapping("/create")
    public R<Integer> create(@RequestBody Robot robot) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", robot.getUid());
        map.put("name", robot.getName());
        map.put("displayName", robot.getNickname());
        map.put("portrait", robot.getAvatar());
        map.put("callback", robot.getCallback());
        map.put("secret", robot.getSecret());
        map.put("robotExtra", robot.getRobotExtra());
        map.put("owner", "admin");
        Result data = APiUtil.getData("admin/robot/create", map);
        R<Integer> result = new R<>();
        result.setCode(data.getCode());
        Map<String, Object> resultMap = (Map<String, Object>) data.getResult();
        String robotID = (String) resultMap.get("userId");
        if (StrUtil.isEmpty(robot.getUid())) {
            if (StrUtil.isNotEmpty(robotID)) {
                List<String> users = new ArrayList<>();
                //将机器人绑定为好友
                List<User> userList = userMapper.selectList(null);
                userList.forEach(o -> {
                    //绑定好友关系
                    bindFriend(robotID, o.getUid(), 0);
                    users.add(o.getUid());
                });
                //推送消息
                sendMsg(users, robotID, robot.getNickname());
                result.setMsg(data.getCode() == 0 ? "添加成功" : data.getMsg());
            }
        } else {
            result.setMsg(data.getCode() == 0 ? "更新成功" : data.getMsg());
        }
        return result;
    }


    /**
     * 删除机器人
     *
     * @param id
     * @return
     */
    @RequestMapping("/remove/{id}")
    public R remove(@PathVariable("id") Integer id) {
        int i = robotMapper.deleteById(id);
        R<Integer> result = new R<>();
        result.setCode(0);
        result.setMsg(i > 0 ? "禁用成功" : "禁用失败");
        return result;
    }

    /**
     * 消息推送
     *
     * @param users
     * @param robotID
     */
    public static void sendMsg(List<String> users, String robotID, String robotName) {
        users.remove(robotID);
        Map<String, Object> map = new HashMap<>();
        //发送者用户ID
        map.put("sender", robotID);
        //群发目标ID
        map.put("targets", users);
        Map<String, Object> payload = new HashMap<>();
        payload.put("type", 1);
        payload.put("searchableContent", "hello，我是" + robotName + "。");
        map.put("payload", payload);
        APiUtil.getData("admin/message/multicast", map);
    }

    /**
     * 绑定好友关系0=好友，1=陌生人
     */
    public static void bindFriend(String userId, String friendUid, int status) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("friendUid", friendUid);
        map.put("status", status);
        APiUtil.getData("/admin/friend/status", map);
    }
}
